// 用于处理主进程和渲染进程的通信
import useAppStore from "@/store/modules/appInfos";

let ipc = null;
// 用于处理shell
let shell = null;

// 初始化ipc
export function ipcInit() {
    try {
        const electron = require('electron');
        ipc = electron.ipcRenderer;
        shell = electron.shell;
        useAppStore().setIpc(ipc);
        useAppStore().setShell(shell);
    } catch (e) {
        console.error('failed to init ipcRenderer:');
        console.error(e);
    }
}

// 显示主窗口
export function windowShow() {
    ipcSend('window-show')
}
// 窗口最小化
export function windowMin() {
    ipcSend('window-min');
}
//窗口最大化
export function windowMax() {
    ipcSend('window-max');
}
//窗口还原
export function windowRestore() {
    ipcSend('window-restore');

}
// 主页面关闭按钮使用退出程序
export function windowQuit() {
    ipcSend("window-quit");

}

// 关闭窗口
export function windowClose() {
    ipcSend('window-close');
}


/**
 * Opens different resources
 * @param appType 1 for web browser, 2 for host
 * @param url
 */
export function openResource(appType, url) {
    if (appType === 1) {
        openBrowser(url);
    }
}

/**
 * Opens the browser
 * @param url
 */
function openBrowser(url) {
    if (shell) {
        shell.openExternal(url);
    } else {
        window.open(url);
    }
}


//通用的发送消息方法
export function ipcSend(message, args) {
    if (ipc) {
        ipc.send(message, args)
    } else {
        console.log(message + " ipc is null")
    }
}

//通用的发送消息方法同步返回
export function ipcSendSync(message, args) {
    if (ipc) {
        return ipc.sendSync(message, args)
    } else {
        console.log(message + " ipc is null")
        return null
    }
}
